//
//  ComplainViewController.m
//  OCPB
//
//  Created by Siroj Chongkolwanont on 6/30/56 BE.
//  Copyright (c) 2556 Siroj Chongkolwanont. All rights reserved.
//

#import "ComplainViewController.h"
#import "SueCase.h"
#import "ComTypeLv0.h"
#import "ComTypeLv1.h"
#import "ComCause.h"
#import "Petitioner_Request.h"
#import "ProjectComplain.h"
#import "SearchProjectViewController.h"
#import "SerchPersonViewController.h"
#import "AddPersonComplainVC.h"
#import "AddProjectComplainViewController.h"
#import <MobileCoreServices/UTCoreTypes.h>
#import "Document.h"
#import "DocumentType.h"
#import <QuartzCore/QuartzCore.h>
#import "UIDeleteButton.h"
#import "UIDocTypeTextField.h"

@interface ComplainViewController ()

@end

@implementation ComplainViewController

@synthesize suePicker;
@synthesize comLv0picker;
@synthesize comLv1Picker;
@synthesize causePicker;
@synthesize amountText;
@synthesize amoutLabel;
@synthesize bathLabel;
@synthesize peReqPicker;
@synthesize scrollView;
@synthesize projectComplainLabel;
@synthesize fileTable;
@synthesize personComplainTable;
@synthesize subjectTxt;
@synthesize detailTxt;
@synthesize authenKey;

@synthesize sueTxt;
@synthesize comLv0Txt;
@synthesize comLv1Txt;
@synthesize causeTxt;
@synthesize peReqTxt;
@synthesize topicPickerView;
@synthesize detailTextView;
@synthesize projectText;
@synthesize personText;

@synthesize currentType;
@synthesize ProjectLabel;
@synthesize PersonLabel;
@synthesize ProjectInd;
@synthesize ProjectButton;
@synthesize currentCom0Type;
@synthesize docTypePicker;
@synthesize docTypeText;
@synthesize activityBar;

@synthesize typeButton;
@synthesize causeButton;
@synthesize purposeButton;


UIActionSheet* aComplainTypeSheet;
UIActionSheet* aCauseSheet;
UIActionSheet* aPurposeSheet;
UIActionSheet* aDocTypeSheet;




id jsonObjectFromUrlString(NSString *urlString);

NSMutableArray *sueCasesArray;
NSMutableArray *comTypeLv0Array;
NSMutableArray *comTypeLv1Array;
NSMutableArray *causeTypeArray;
NSMutableArray* peRequestArray;
NSMutableArray* documentTypeArray;

NSMutableArray* documentArray;
NSMutableArray* personComplainArray;


SueCase* currentSue;
ComTypeLv0* currentComLv0;
ComTypeLv1* currentComLv1;
ComCause* currentCause;
Petitioner_Request* currentPeReq;
ProjectComplain* currentProject;
DocumentType* currentDocType;
Document* currentDoc;
UITextField* currentTextView;

UITextView* currentTView;

NSInteger currentTopic = 0;


UIButton* currentDocButton;

bool is_delete = false;





-(BOOL)textFieldShouldReturn:(UITextField*)textField;
{
    [textField resignFirstResponder];
    
   if(textField == subjectTxt)
   {
       [typeButton sendActionsForControlEvents: UIControlEventTouchUpInside];

   }
    return NO; // We do not want UITextField to insert line-breaks.
}



- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
{
    // The number of sections in the UIPickerView
    
    return 1;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
{
    // The number of rows in the UIPickerView
    //return [pickerData count];
    
    if(pickerView == suePicker)
    {
        return [sueCasesArray count];
    }
    else if (pickerView == comLv0picker)
    {
        return [comTypeLv0Array count];
    }
    else if (pickerView == comLv1Picker)
    {
        return [comTypeLv1Array count];
    }
    else if (pickerView == causePicker)
    {
        return [causeTypeArray count];
    }
    else if (pickerView == peReqPicker)
    {
        return [peRequestArray count];
    }
    
    else if (pickerView == docTypePicker)
    {
        return [documentTypeArray count];
    }
    
    
    return  0;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;
{
    // The data for each row in the UIPickerView
    //return [pickerData objectAtIndex:row];
    
    if(pickerView == suePicker)
    {
        return  ((SueCase*)sueCasesArray[row]).sue_name;
    }
    else if(pickerView == comLv0picker)
    {
        return  ((ComTypeLv0*)comTypeLv0Array[row]).name;
    }
    else if(pickerView == comLv1Picker)
    {
        return  ((ComTypeLv1*)comTypeLv1Array[row]).name;
    }
    else if (pickerView == causePicker)
    {
        return ((ComCause*)causeTypeArray[row]).cause_name;
    }
    else if (pickerView == peReqPicker)
    {
        return ((Petitioner_Request*)peRequestArray[row]).name;
    }
    
    else if (pickerView == docTypePicker)
    {
       return ((DocumentType*)documentTypeArray[row]).document_name;
    }
    
    return @"A";
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    // whatever you want to happen when a row is selected.
    
    // here I am assuming you want to remove from the picker and add to the table on selection
    if(pickerView == comLv0picker)
    {
        [self load_comLv1:comTypeLv0Array[row]];
        [self load_cause:comTypeLv1Array[row]];
        
        [comLv1Picker reloadAllComponents];
        [causePicker reloadAllComponents];
        
        currentComLv0 = comTypeLv0Array[row];
        
    }
    else if(pickerView == comLv1Picker)
    {
        [self load_cause:comTypeLv1Array[row]];
        [causePicker reloadAllComponents];
        
        currentComLv1 = comTypeLv1Array[row];
        
    }
    else if(pickerView == suePicker)
    {
        currentSue = sueCasesArray[row];
    }
    else if (pickerView == causePicker)
    {
        currentCause = causeTypeArray[row];
    }
    
    else if(pickerView == peReqPicker)
    {
        
        currentPeReq = peRequestArray[row];
        
        if(currentPeReq.amount_flag)
        {
            [self showAmount];
            
        }
        else
        {
            [self hideAmount];
        }
    }
    else if(pickerView == docTypePicker)
    {
        currentDocType = documentTypeArray[row];
        if(documentArray.count > 0)
        {
            UIDocTypeTextField* docTypeField = (UIDocTypeTextField*)currentTextView;
            
            Document* doc = documentArray[docTypeField.row ];
            
            doc.Document_id = currentDocType.document_id;
            doc.Document_TypeName = currentDocType.document_name;
            doc.Document_index = row;
            docTypeField.text = doc.Document_TypeName;
        }
    }
    else
    {

        
    }
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
}

- (BOOL)textView:(UITextView *)textView
shouldChangeTextInRange:(NSRange)range
 replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"])
    {
        [textView resignFirstResponder];
    }
    return YES;
}

- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

{
    
    if ([string length] == 0 && range.length > 0)
    {
        return YES;
    }
    
    
    if ([string isEqualToString:@"\n"])
    {
        [textField resignFirstResponder];
    }
    return YES;
    
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)load_sueCases
{
    sueCasesArray = [[NSMutableArray alloc] init];
    
    NSDictionary *publicTimeline =  jsonObjectFromUrlString(@"http://www.aitproject.com/demo/webservice/public/service/sue-case");
    
    aPurposeSheet = [[UIActionSheet alloc] initWithTitle:@"เลือกความประสงค์ในการร้องทุกข์" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil, nil];
    
    
    for(NSString *item in [publicTimeline allKeys]) {
        
        if([item isEqual: @"data"] )
        {
            NSDictionary *allData = [publicTimeline valueForKey:item];
            
                    NSArray *allSue = [allData valueForKey:item];
                    
                    for(NSDictionary *data in allSue )
                    {
                        
                        SueCase* sue_case = [[SueCase alloc] init];
                        sue_case.sue_id = [data valueForKey:@"Sue_case_id"];
                        sue_case.sue_name = [data valueForKey:@"Sue_case_Name"];
                        
                        [sueCasesArray addObject:sue_case];
                        
                        [aPurposeSheet addButtonWithTitle:sue_case.sue_name];

                        
                    }
            
        }
    }
    
    currentSue = sueCasesArray[0];
}

-(void) load_comLv0
{
    comTypeLv0Array = [[NSMutableArray alloc] init];
    
    NSDictionary *publicTimeline =  jsonObjectFromUrlString(@"http://www.aitproject.com/demo/webservice/public/service/complain-type?type=lv0");
    
    
    for(NSString *item in [publicTimeline allKeys]) {
        
        if([item isEqual: @"data"] )
        {
            NSDictionary *allData = [publicTimeline valueForKey:item];
            
            NSArray *allSue = [allData valueForKey:item];
            
            for(NSDictionary *data in allSue )
            {
                
                ComTypeLv0* comLv0 = [[ComTypeLv0 alloc] init];
                comLv0.type_id = [data valueForKey:@"Complain_Type_Id"];
                comLv0.level = [data valueForKey:@"Complain_Type_Level"];
                comLv0.refer = [data valueForKey:@"Complain_Type_Refer"];
                comLv0.name = [data valueForKey:@"Complain_Type_Name"];
                
                [comTypeLv0Array addObject:comLv0];
                
            }
            
        }
    }
    
    currentComLv0 = comTypeLv0Array[[currentType intValue]];
}

-(void) load_comLv1:(ComTypeLv0*)currentComLv0
{
    comTypeLv1Array = [[NSMutableArray alloc] init];
    
    aComplainTypeSheet = [[UIActionSheet alloc] initWithTitle:@"เลือกประเภทเรื่องร้องทุกข์" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil, nil];
    

    NSString *url_str = [NSString stringWithFormat:@"http://www.aitproject.com/demo/webservice/public/service/complain-type?type=lv1&ref_id=%@", currentComLv0.type_id];
    
    NSDictionary *publicTimeline =  jsonObjectFromUrlString(url_str);
    
    
    for(NSString *item in [publicTimeline allKeys]) {
        
        if([item isEqual: @"data"] )
        {
            NSDictionary *allData = [publicTimeline valueForKey:item];
            
            NSArray *allSue = [allData valueForKey:item];
            
            for(NSDictionary *data in allSue )
            {
                
                ComTypeLv1* comLv1 = [[ComTypeLv1 alloc] init];
                comLv1.type_id = [data valueForKey:@"Complain_Type_Id"];
                comLv1.level = [data valueForKey:@"Complain_Type_Level"];
                comLv1.refer = [data valueForKey:@"Complain_Type_Refer"];
                comLv1.name = [data valueForKey:@"Complain_Type_Name"];
                
                [comTypeLv1Array addObject:comLv1];
                
                [aComplainTypeSheet addButtonWithTitle:comLv1.name];
                
            }
        }
    }
    
    currentComLv1 = comTypeLv1Array[0];
}

-(void) load_cause:(ComTypeLv1*)currentComLv1
{
    causeTypeArray = [[NSMutableArray alloc] init];
    
    
    aCauseSheet = [[UIActionSheet alloc] initWithTitle:@"เลือกสาเหตุเรื่องร้องทุกข์" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil, nil];

    NSString *url_str = [NSString stringWithFormat:@"http://www.aitproject.com/demo/webservice/public/service/complain-cause?type_id=%@", currentComLv1.type_id];
    
    NSDictionary *publicTimeline =  jsonObjectFromUrlString(url_str);
    
    
    for(NSString *item in [publicTimeline allKeys]) {
        
        if([item isEqual: @"data"] )
        {
            NSDictionary *allData = [publicTimeline valueForKey:item];
            
            NSArray *allSue = [allData valueForKey:item];
            
            for(NSDictionary *data in allSue )
            {
                
                ComCause* comCause = [[ComCause alloc] init];
                comCause.cause_id = [data valueForKey:@"Complain_Cause_id"];
                comCause.cause_name = [data valueForKey:@"Complain_Cause_Name"];
                comCause.type_id = [data valueForKey:@"Complain_Type_id"];
                
                [causeTypeArray addObject:comCause];
                [aCauseSheet addButtonWithTitle:comCause.cause_name];
                
            }
        }
    }
    
    if([causeTypeArray count] > 0)
    
    currentCause = causeTypeArray[0];
}

-(void) load_peRequest
{
    peRequestArray = [[NSMutableArray alloc] init];
    
    

    
    
    NSString *url_str = [NSString stringWithFormat:@"http://www.aitproject.com/demo/webservice/public/service/petitioner-request"];
    
    NSDictionary *publicTimeline =  jsonObjectFromUrlString(url_str);
    
    
    for(NSString *item in [publicTimeline allKeys]) {
        
        if([item isEqual: @"data"] )
        {
            NSDictionary *allData = [publicTimeline valueForKey:item];
            
            NSArray *allSue = [allData valueForKey:item];
            
            for(NSDictionary *data in allSue )
            {
                
                Petitioner_Request* peReq = [[Petitioner_Request alloc] init];
                peReq.id = [data valueForKey:@"Petitioner_request_id"];
                peReq.name = [data valueForKey:@"Petitioner_request_Name"];
                peReq.amount_flag = [[data valueForKey:@"Petitioner_request_amount_flag"] integerValue];
                
                [peRequestArray addObject:peReq];
                
            }
        }
    }
    
    currentPeReq = peRequestArray[0];
    
    if(currentPeReq.amount_flag)
    {
        [self showAmount];
        
    }
    else
    {
        [self hideAmount];
    }
}

-(void) load_documentType
{
    documentTypeArray = [[NSMutableArray alloc] init];
    
    
    NSString *url_str = [NSString stringWithFormat:@"http://www.aitproject.com/demo/webservice/public/service/document"];
    
    NSDictionary *publicTimeline =  jsonObjectFromUrlString(url_str);
    
    aDocTypeSheet = [[UIActionSheet alloc] initWithTitle:@"เลือกชนืดหลักฐาน" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil, nil];

    
    for(NSString *item in [publicTimeline allKeys]) {
        
        if([item isEqual: @"data"] )
        {
            NSDictionary *allData = [publicTimeline valueForKey:item];
            
            NSArray *allSue = [allData valueForKey:item];
            
            for(NSDictionary *data in allSue )
            {
                
                DocumentType* docType = [[DocumentType alloc] init];
                docType.document_id = [data valueForKey:@"Document_id"];
                docType.document_name = [data valueForKey:@"Document_Name"];
                docType.document_qty = [data valueForKey:@"Qty_Show"];
                docType.document_date = [data valueForKey:@"Date_Show"];
                
                [documentTypeArray addObject:docType];
                
                [aDocTypeSheet addButtonWithTitle:docType.document_name];

                
            }
        }
    }
    
    currentDocType = documentTypeArray[0];
}

- (void)showAmount
{
    amoutLabel.hidden = false;
    amountText.hidden = false;
    bathLabel.hidden = false;
    
}

- (void)hideAmount
{
    amoutLabel.hidden = true;
    amountText.hidden = true;
    bathLabel.hidden = true;
    
}

- (void)viewDidLoad
{    
    [self load_sueCases];
    [self load_comLv0];
    [self load_comLv1:comTypeLv0Array[[currentType intValue]]];
    [self load_cause:comTypeLv1Array[0]];
    [self load_peRequest];
    [self load_documentType];
    
    if([currentType intValue] == 0 )
    {
        ProjectButton.hidden = NO;
        ProjectLabel.hidden = NO;
        ProjectInd.hidden = NO;
        
    }
    else
    {
        ProjectButton.hidden = YES;
        ProjectLabel.hidden = YES;
        ProjectInd.hidden = YES;
    }
    
     documentArray = [[NSMutableArray alloc] init];
     personComplainArray = [[NSMutableArray alloc] init];
	// Do any additional setup after loading the view.
    
    
    sueTxt.inputView = suePicker;
    comLv0Txt.inputView = comLv1Picker;
    comLv1Txt.inputView = comLv1Picker;
    causeTxt.inputView = causePicker;
    peReqTxt.inputView = peReqPicker;
    docTypeText.inputView = docTypePicker;
    
    //subjectTxt.inputView = topicPickerView;
    
    [[detailTextView layer] setBorderColor:[[UIColor lightGrayColor] CGColor]];
    [[detailTextView layer] setBorderWidth:2.3];
    [[detailTextView layer] setCornerRadius:15];

    [super viewDidLoad];
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed: @"22Navigation_background_320x46.png"]
                                                  forBarMetrics:UIBarMetricsDefault];
    
    UIButton *button1 = [[UIButton alloc] init];
    button1.frame= CGRectMake(0,0,43,32);
    [button1 setBackgroundImage:[UIImage imageNamed: @"icon_back"] forState:UIControlStateNormal];
    
    [button1 addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button1];
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
                                   initWithTarget:self
                                   action:@selector(dismissKeyboard)];
    
    [self.view addGestureRecognizer:tap];
    
    
    
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    currentTView = textView;
    
    UIScrollView* v = (UIScrollView*) scrollView ;
    CGRect rc = [currentTView bounds];
    rc = [currentTView convertRect:rc toView:v];
    
    rc.origin.x = 0 ;
    rc.origin.y -= 60 ;
    
    rc.size.height = 400;
    [scrollView setContentOffset:CGPointMake(rc.origin.x, rc.origin.y)
                        animated:YES];
}

-(void)dismissKeyboard {
    
    if(currentTextView != Nil)
        [currentTextView resignFirstResponder];
    
    if(currentTView != Nil)
        [currentTView resignFirstResponder];
}

- (void)doneTapped
{
   
    
}

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    if(textField.tag == 1 )
        topicPickerView.hidden = NO;
    else if (textField.tag ==2 )
        comLv0picker.hidden = NO;
    else if (textField.tag ==3 )
        comLv1Picker.hidden = NO;
    else if (textField.tag ==4 )
        causePicker.hidden = NO;
    else if (textField.tag ==8 )
        suePicker.hidden = NO;
    else if (textField.tag ==202 )
    {
        UIDocTypeTextField* docTypeField = (UIDocTypeTextField*)textField;
        currentDoc = documentArray[docTypeField.row];
        
        [docTypePicker selectRow:currentDoc.Document_index inComponent:0 animated:NO];
        
        docTypePicker.hidden = NO;
    }
        
    
    
    currentTextView = textField;
    
    UIScrollView* v = (UIScrollView*) scrollView ;
    CGRect rc = [currentTextView bounds];
    rc = [currentTextView convertRect:rc toView:v];
    
    rc.origin.x = 0 ;
    rc.origin.y -= 60 ;
    
    rc.size.height = 400;
    [scrollView setContentOffset:CGPointMake(rc.origin.x, rc.origin.y)
                        animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) setProjectComplain:(ProjectComplain*) project
{
    currentProject = project;
    
    //projectComplainLabel.text = currentProject.project_name;
    
   // projectText.text = currentProject.project_name;
    
    ProjectLabel.text = currentProject.project_name;
    
}

- (IBAction)addCamera:(id)sender {
    
    [currentTView resignFirstResponder];
    [currentTextView resignFirstResponder];
    
    
    UIImagePickerController *imagePicker =
    [[UIImagePickerController alloc] init];
    
    imagePicker.delegate = self;
    
    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    
    
    imagePicker.allowsEditing = NO;
    
    
    
    [self presentViewController:imagePicker animated:YES completion:NULL];
    
    //[scrollView setContentOffset:CGPointMake(self.scrollView.contentOffset.x, 0)
     //                   animated:NO];
}

- (void) addPersonComplain:(PersonComplain *)person
{
    [personComplainArray addObject:person];
    
    //personText.text = person.person_name;
    //[personComplainTable setEditing:YES];
    //[personComplainTable reloadData];
    
    PersonLabel.text = person.person_name;
    
}

- (IBAction)addFileClick:(id)sender {
    
    [currentTView resignFirstResponder];
    [currentTextView resignFirstResponder];
    
    
    UIImagePickerController *imagePicker =
    [[UIImagePickerController alloc] init];
        
    imagePicker.delegate = self;
    
    imagePicker.sourceType =
    UIImagePickerControllerSourceTypePhotoLibrary;
    
    
    imagePicker.allowsEditing = NO;
    

    
    [self presentViewController:imagePicker animated:YES completion:NULL];
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    
    if(picker.sourceType == UIImagePickerControllerSourceTypeCamera )
    {
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    }
    
    NSData* imageData = UIImageJPEGRepresentation(image, 1.0);
    
    //NSString* incrementedImgStr = [NSString stringWithFormat: @"UserCustomPotraitPic%d.jpg", IMAGE_COUNTER];
    
    NSURL *imagePath = [info objectForKey:@"UIImagePickerControllerReferenceURL"];
    
    NSString *imageName = [imagePath path];
    
    NSArray *parts = [imageName componentsSeparatedByString:@"/"];
    NSString *filename = [parts objectAtIndex:[parts count]-1];
    
    NSLog(@"Image Path = %@",imageName);
    
    Document* doc = [[Document alloc] init];
    
    doc.Document_path = filename;
    doc.imageData = imageData;
    doc.Document_id = ((DocumentType*)documentTypeArray[0]).document_id;
    doc.Document_TypeName = ((DocumentType*)documentTypeArray[0]).document_name;
    doc.Document_index = 0;
    
    
    [documentArray addObject:doc];
    is_delete = false;
    [fileTable reloadData];
    [picker dismissViewControllerAnimated:YES completion:NULL];
    
    
}


- (void) imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    // [scrollView setContentOffset:CGPointMake(x, y)
    //                     animated:NO];
    
    [picker dismissViewControllerAnimated:YES completion:NULL];
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSInteger row = [documentArray count];
    
    return row;
}

-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    
    // Configure the cell...
    if (cell == nil) {
    }
    
    NSInteger row = indexPath.row;
    
    
    Document* doc = documentArray[row];
        
        
    UIImageView *image = (UIImageView *)[cell viewWithTag:100];
    UIImage *img = [UIImage imageWithData:doc.imageData];
    image.image = img;
        
    UIDeleteButton *deleteBtn = (UIDeleteButton *)[cell viewWithTag:101];
        
    deleteBtn.row = row;
        
    

    
    
    
    UIDeleteButton *fileType = (UIDeleteButton *)[cell viewWithTag:200];
    fileType.row = row;
    [fileType setTitle:doc.Document_TypeName forState:UIControlStateNormal];

    
    if(row == documentArray.count - 1 && is_delete == false)
    [fileType sendActionsForControlEvents: UIControlEventTouchUpInside];

    
    
    return cell;
    
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(tableView == personComplainTable)
    {
        
        return [personComplainArray count];
    }
    
    NSInteger row = [documentArray count];
    
    return row;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return YES if you want the specified item to be editable.
    return YES;
}
- (UITableViewCell *)tableView:(UITableView *)tableView1 cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView1 dequeueReusableCellWithIdentifier:CellIdentifier];
    
    // Configure the cell...
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    NSInteger row = indexPath.row;
    
    
    {
        PersonComplain* person = personComplainArray[row];
        
        
        UILabel *typeName = (UILabel *)[cell viewWithTag:100];
        typeName.text = person.person_type_name;
        
        UILabel *personName = (UILabel *)[cell viewWithTag:101];
        personName.text = person.person_name;
        
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete ) {
        int row = indexPath.row;
        

        {
            [personComplainArray removeObjectAtIndex:row];
            [personComplainTable reloadData];
        }
    }
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    [scrollView setContentOffset:CGPointMake(self.scrollView.contentOffset.x, 0)
                        animated:NO];
    [currentTView resignFirstResponder];
    [currentTextView resignFirstResponder];
    
    if([segue.identifier isEqualToString:@"ToProject"])
    {
        AddProjectComplainViewController *p = (AddProjectComplainViewController*)segue.destinationViewController;
        p.complainController = self;
    }
    else if ([segue.identifier isEqualToString:@"ToPerson"])
    {
        AddPersonComplainVC *p = (AddPersonComplainVC*)segue.destinationViewController;
        p.complainController = self;
    }
    
    
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    NSError *error = nil;
    //NSString *jsonResponse =  [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSDictionary* jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    
    NSString* error_code = [jsonObject valueForKey:@"error_code"];
    
    NSDictionary* complain_dict = [jsonObject valueForKey:@"data"];
    
    NSString* complainId = [complain_dict valueForKey:@"Complain_id"];
    
    
    NSString *jsonRequest =  [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    NSLog(@"jsonResponse is %@", jsonRequest);
    
    if(error_code.intValue > 0)
    {
        UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"ร้องทุกข์!"
                                                          message:[jsonObject valueForKey:@"message"]
                                                         delegate:nil
                                                cancelButtonTitle:@"OK"
                                                otherButtonTitles:nil];
        [message show];
        [activityBar stopAnimating];
        
    }
    else
    {
        
        [self sendFiles:complainId];

    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"ร้องทุกข์"
                                                      message:@"ไม่สามารถเชื่อมต่ออินเตอร์เน็ทได้ กรุณาตรวจสอบการตั้งค่าที่โทรศัพท์"
                                                     delegate:nil
                                            cancelButtonTitle:@"OK"
                                            otherButtonTitles:nil];
    [message show];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"%s", __FUNCTION__);
}


- (void)sendFiles:(NSString*) complainId
{    
    __block NSInteger nFile = [documentArray count];
    
    if(nFile == 0)
    {
        UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"ร้องทุกข์!"
                                                          message:[NSString stringWithFormat:@"ขอบคุณสำหรับเรื่องร้องทุกข์ของท่าน ทาง สคบ. ได้รับเรื่องร้องทุกข์ของท่านแล้ว"]                                                       delegate:nil
                                                cancelButtonTitle:@"ปิด"
                                                otherButtonTitles:nil];
        [message show];
        [activityBar stopAnimating];
        
        [self.navigationController popViewControllerAnimated:YES];


    }
    
    for(int i=0; i<[documentArray count]; i++)
    {
        Document* document = [documentArray objectAtIndex:i];
        
        NSString* doc_name = [NSString stringWithFormat:@"%@%d",document.Document_path,i];
        
       NSString* urlstr = [NSString stringWithFormat:@"http://www.aitproject.com/demo/webservice/public/service/attach-file?Complain_id=%@&Document_id=%@",complainId,document.Document_id];
        NSLog(@"ีurl = %@",urlstr);
        
        NSURL *url = [NSURL URLWithString:urlstr];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        
        [request setHTTPMethod:@"POST"];
        [request setValue:authenKey forHTTPHeaderField:@"Authorization"];
        
        NSString *boundary = @"---------------------------14737809831466499882746641449";
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
        [request addValue:contentType forHTTPHeaderField:@"Content-Type"];
        
        //Add Form
        NSMutableData *body = [NSMutableData data];
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: attachment; name=\"file\";filename=\"%@\"\r\n", doc_name] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:document.imageData];
        [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        
        //Close Form
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [request setHTTPBody:body];
        
        [NSURLConnection sendAsynchronousRequest:request
                                           queue:[NSOperationQueue mainQueue]
                               completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                                   nFile--;
                                   NSLog(@"%@",data);
                                   NSString *returnstring=[[NSString alloc]initWithData:data encoding:NSASCIIStringEncoding];
                                   NSLog(@"%@",returnstring);
                                  
                                   NSDictionary* jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
                                   
                                   NSString* error_code = [jsonObject valueForKey:@"error_code"];
                                   
                                   if(error_code.intValue > 0)
                                   {
                                       UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"ร้องทุกข์!"
                                                                                         message:[jsonObject valueForKey:@"message"]
                                                                                        delegate:nil
                                                                               cancelButtonTitle:@"OK"
                                                                               otherButtonTitles:nil];
                                       [message show];
                                       
                                   }
                                   else
                                   {
     
                                   }
                                   
                                   if (nFile == 0) {
                                       
                                       UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"ร้องทุกข์!"
                                                                                         message:[NSString stringWithFormat:@"ขอบคุณสำหรับเรื่องร้องทุกข์ของท่าน ทาง สคบ. ได้รับเรื่องร้องทุกข์ของท่านแล้ว"]                                                       delegate:nil
                                                                               cancelButtonTitle:@"ปิด"
                                                                               otherButtonTitles:nil];
                                       [message show];
                                       [activityBar stopAnimating];
                                       [self.navigationController popViewControllerAnimated:YES];


                                       
                                   }
                               }
         
         ];
        

    }
}

- (IBAction)backAction:(id)sender {
    
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)createComplain:(id)sender {
    
    NSString* com_type_Lv0;
    NSString* com_type_Lv1;
    
    
    if([subjectTxt.text isEqual: @""] ||[ProjectLabel.text isEqual: @""]  || [detailTextView.text isEqual: @""]  )
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ร้องทุกข์" message:@"กรุณาใส่ข้อมูลให้ครบถ้วน"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        
        return;
        
    }
    
    
    
    if(currentComLv0.type_id.intValue < 100)
    {
        com_type_Lv0 = [NSString stringWithFormat:@"0%d", currentComLv0.type_id.intValue];
    }
    else if(currentComLv0.type_id.intValue < 10)
    {
        com_type_Lv0 = [NSString stringWithFormat:@"00%d", currentComLv0.type_id.intValue];
    }
    else
    {
        com_type_Lv0 = [NSString stringWithFormat:@"%d", currentComLv0.type_id.intValue];
    }
    
    if(currentComLv1.type_id.intValue < 100)
    {
        com_type_Lv1 = [NSString stringWithFormat:@"0%d", currentComLv1.type_id.intValue];
    }
    else if(currentComLv1.type_id.intValue < 10)
    {
        com_type_Lv1 = [NSString stringWithFormat:@"00%d", currentComLv1.type_id.intValue];
    }
    else
    {
        com_type_Lv1 = [NSString stringWithFormat:@"%d", currentComLv1.type_id.intValue];
    }
    
   
    currentCause =  causeTypeArray[0];
    
    NSArray* complain_objects = [NSArray arrayWithObjects:subjectTxt.text
                                 , detailTextView.text
                                 , currentCause.cause_id
                                 , com_type_Lv1
                                 , currentSue.sue_id
                                 , currentPeReq.id
                                 , @""
                                 ,nil];
    
    NSArray *complain_keys = [NSArray arrayWithObjects:@"Complain_Subject"
                     ,@"Complain_Details"
                     ,@"Complain_Cause_id"
                     ,@"Complain_type_id"
                     ,@"Sue_case_id"
                     ,@"Petitioner_request_id"
                     ,@"Request_Amount"
                     ,nil];
    
    NSDictionary *json_complain = [NSDictionary dictionaryWithObjects:complain_objects forKeys:complain_keys];
    
    NSMutableArray* person_array = [[NSMutableArray alloc] init];
    
    for (int i=0; i<[personComplainArray count]; i++)
    {
        [person_array addObject: ((PersonComplain *)[personComplainArray objectAtIndex:i]).person_id];
    }
    
    
    NSString *current_proj = @"0";
    
    if(currentProject != NULL)
    {
        current_proj = currentProject.project_id;
    }
    
    NSArray *objects = [NSArray arrayWithObjects:json_complain
                        , person_array
                        , current_proj
                        ,nil];
    NSArray *keys = [NSArray arrayWithObjects:@"complain"
                     ,@"person_complained_id"
                     ,@"person_complained_project_id"
                     ,nil];
    NSDictionary *jsonDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
    
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];
    
    
    NSString *jsonRequest = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSLog(@"jsonRequest is %@", jsonRequest);
    
    NSURL *url = [NSURL URLWithString:@"http://www.aitproject.com/demo/webservice/public/service/complain"];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    
    NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding]; //[NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
    
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:authenKey forHTTPHeaderField:@"Authorization"];
    [request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
    
    [request setHTTPBody: requestData];
    
    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    
    
    CGPoint center = scrollView.contentOffset;
    
    center.x = activityBar.center.x;
    
    center.y += 100;
    
    activityBar.center = center;
    
    
    [activityBar startAnimating];
    
    if (connection) {
    }
}
- (void)viewDidUnload {
    [self setTopicPickerView:nil];
    [self setFileTable:nil];
    [self setDetailTextView:nil];
    [self setProjectText:nil];
    [self setPersonText:nil];
    [super viewDidUnload];
}
- (IBAction)delete_picture:(id)sender {
    UIDeleteButton *buttontag = (UIDeleteButton *)sender;
    //NSLog(@"%d",buttontag.tag);
    NSInteger Delete_row = buttontag.row;
    
    [documentArray removeObjectAtIndex:Delete_row];
    is_delete = true;
    [fileTable reloadData];
}
- (IBAction)selectList:(id)sender {
    
    [self showAction:sender];
}

- (IBAction)selectDocType:(id)sender {
    
    UIActionSheet *asheet = aDocTypeSheet;
    
    currentDocButton = sender;
    
    [asheet setFrame:CGRectMake(0, 117, 320, 383)];
    
    [asheet showInView:[self.view superview]];
    
    
    UIScrollView* v = (UIScrollView*) scrollView ;
    CGRect rc = [sender bounds];
    rc = [sender convertRect:rc toView:v];
    
    rc.origin.x = 0 ;
    rc.origin.y -= 60 ;
    
    rc.size.height = 400;
    [scrollView setContentOffset:CGPointMake(rc.origin.x, rc.origin.y)
                        animated:YES];
}

-(void) showAction:(id)sender
{
    UIActionSheet *asheet = nil;
    
    [currentTextView resignFirstResponder];
    
    if(sender == typeButton)
    {
        asheet = aComplainTypeSheet;
    }
    else if (sender == causeButton)
    {
        asheet = aCauseSheet;
    }
    else if (sender == purposeButton)
    {
        asheet = aPurposeSheet;
    }
    
    [asheet setFrame:CGRectMake(0, 117, 320, 383)];
    
    [asheet showInView:[self.view superview]];
    
    
    UIScrollView* v = (UIScrollView*) scrollView ;
    CGRect rc = [sender bounds];
    rc = [sender convertRect:rc toView:v];
    
    rc.origin.x = 0 ;
    rc.origin.y -= 60 ;
    
    rc.size.height = 400;
    [scrollView setContentOffset:CGPointMake(rc.origin.x, rc.origin.y)
                        animated:YES];
}


- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //Get the name of the current pressed button
    
    if(actionSheet == aComplainTypeSheet)
    {
        currentComLv1 = comTypeLv1Array[buttonIndex];
        [typeButton setTitle:currentComLv1.name forState:UIControlStateNormal];
        [self load_cause:currentComLv1];
        
        [causeButton sendActionsForControlEvents: UIControlEventTouchUpInside];
        
    }
    else if (actionSheet == aCauseSheet)
    {
        currentCause = causeTypeArray[buttonIndex];
        [causeButton setTitle:currentCause.cause_name forState:UIControlStateNormal];

                
    }
    else if(actionSheet == aPurposeSheet)
    {
        currentSue = sueCasesArray[buttonIndex];
        [purposeButton setTitle:currentSue.sue_name forState:UIControlStateNormal];
        
    }
    else if (actionSheet == aDocTypeSheet)
    {
        
        UIDeleteButton *buttontag = (UIDeleteButton *)currentDocButton;
        NSInteger row = buttontag.row;
       
        currentDoc = documentArray[row];
        currentDocType = documentTypeArray[buttonIndex];
        currentDoc.Document_TypeName = currentDocType.document_name;
      [currentDocButton setTitle:currentDocType.document_name forState:UIControlStateNormal];
       currentDoc.Document_id = currentDocType.document_id;
        
    }
    
    
}
@end
